<template>
  <div class="editor-wrapper">
    <div ref="editor"></div>
  </div>
</template>

<script>
import Editor from 'wangeditor'
import 'wangeditor/release/wangEditor.min.css'
import { oneOf } from '@/libs/tools'
import { upload } from '../../libs/url'
export default {
  name: 'Editor',
  model: {
    prop: 'value'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    /**
     * 绑定的值的类型, enum: ['html', 'text']
     */
    valueType: {
      type: String,
      default: 'html',
      validator: (val) => {
        return oneOf(val, ['html', 'text'])
      }
    },
    /**
     * @description 设置change事件触发时间间隔
     */
    changeInterval: {
      type: Number,
      default: 200
    }
  },
  methods: {
    setHtml (val) {
      this.editor.txt.html(val)
    }
  },
  mounted () {
    this.editor = new Editor(this.$refs.editor)
    this.editor.customConfig.onchange = (html) => {
      let text = this.editor.txt.text()
      this.$emit('input', this.valueType === 'html' ? html : text)
      this.$emit('on-change', html, text)
    }
    this.editor.customConfig.onchangeTimeout = this.changeInterval
    this.editor.customConfig.zIndex = 1000000
    this.editor.customConfig.menus = [
      'head',
      'bold',
      'fontSize',
      'fontName',
      'italic',
      'underline',
      'strikeThrough',
      'indent',
      'lineHeight',
      'foreColor',
      'backColor',
      'link',
      'list',
      'todo',
      'justify',
      'quote',
      'emoticon',
      'image',
      'splitLine',
      'undo',
      'redo'
    ]
    this.editor.customConfig.customUploadImg = function (resultFiles, insertImgFn) {
      resultFiles.forEach((item) => {
        let oFormDate = new FormData()
        oFormDate.append('image', item)
        upload('upload/image', oFormDate)
          .then((res) => {
            let { code, data } = res.data
            if (code === 0) {
              insertImgFn(data.src)
            }
          })
      })
    }
    // create这个方法一定要在所有配置项之后调用
    this.editor.create()
    setTimeout(() => {
      this.editor.txt.html(this.value)
    }, 1000)
  }
}
</script>
